package com.suixingfu.service;

import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;

import com.alibaba.fastjson.JSONObject;
import com.suixingfu.utils.Base64Utils;
import com.suixingfu.utils.DESUtils;
import com.suixingfu.utils.JsonUtils;
import com.suixingfu.utils.PublicPartUtils;
import com.suixingfu.utils.RSAUtils;
import com.suixingfu.vo.RequestMessage;


public class FuKuan {
	public static String getfukuan(JSONObject json3) throws UnsupportedEncodingException, Exception{	
	
//		String json ="{'clientId':'836100058122636','version':'1.0','reqId':'2016080516091210001','tranCd':'DF1003',"
//				+ "'reqData':{'clientId':'836100058122636','payTyp':'01' ,'totalPayCount':'5','totalPayAmt':'150','payItems':["+
//		"{'payItemId':'2016080516091211001','seqNo':'1','payAmt':'10','actNm':'黄霞','actNo':'4563511900008655595','actTyp':'01','bnkCd':'104','bnkNm':'中国银行','lbnkNo':'','lbnkNm':'','rmk':'代付1','smsFlg':'0','tel':'13719190855',' bankPayPurpose ':'打款'},"+
//		"{'payItemId':'2016080516091211002','seqNo':'2','payAmt':'20','actNm':'周康艳','actNo':'43110219871021101X','actTyp':'01','bnkCd':'102','bnkNm':'中国工商银行','lbnkNo':'','lbnkNm':'','rmk':'代付2','smsFlg':'0','tel':'18680302787','bankPayPurpose':'打款'}"+
//		"{'payItemId':'2016080516091211003','seqNo':'3','payAmt':'30','actNm':'王文逸','actNo':'321283198811060650','actTyp':'01','bnkCd':'105','bnkNm':'中国建设银行','lbnkNo':'','lbnkNm':'','rmk':'代付3','smsFlg':'0','tel':'18205276689','bankPayPurpose':'打款'}"+
//		"{'payItemId':'2016080516091211004','seqNo':'4','payAmt':'40','actNm':'陈怡君','actNo':'310107198610260416','actTyp':'01','bnkCd':'102','bnkNm':'中国工商银行','lbnkNo':'','lbnkNm':'','rmk':'代付4','smsFlg':'0','tel':'15001870150','bankPayPurpose':'打款'}"+
//		"{'payItemId':'2016080516091211005','seqNo':'5','payAmt':'50','actNm':'许志钦','actNo':'445122199202023819','actTyp':'01','bnkCd':'102','bnkNm':'中国工商银行','lbnkNo':'','lbnkNm':'','rmk':'代付5','smsFlg':'0','tel':'15913146354','bankPayPurpose':'打款'}"
//		+"]}}";
		String json2=JSONObject.toJSONString(json3);
		String json1=json2.replace("\"", "\'");
		String json=json1.replace("\\", "");
		System.out.println("json="+json);
		
		RequestMessage erm = JsonUtils.fromJson(json, RequestMessage.class);
		
		String reqData = erm.getReqData();

		// DES密钥加密
		String DESkey = PublicPartUtils.DESkey;
		byte[] bs = DESUtils.encrypt(reqData.getBytes("UTF-8"), DESkey);
		// 编码
		String reqDataEncrypt = Base64Utils.encode(bs);
		erm.setReqData(reqDataEncrypt);

		// 合作商私钥签名
		String RSAKey = PublicPartUtils.RSAKey;
		erm.setSign(RSAUtils.sign(reqDataEncrypt, RSAKey));

		System.out.println("erm="+JsonUtils.toJson(erm));
		String jstr = JsonUtils.toJson(erm);
		String url = PublicPartUtils.url+"paygateway/pay.do";

		URL urlt = new URL(url);
		URLConnection urlConnection = urlt.openConnection();
		// 设置doOutput属性为true表示将使用此urlConnection写入数据
		urlConnection.setDoOutput(true);
		// 定义待写入数据的内容类型，我们设置为application/x-www-form-urlencoded类型
		urlConnection.setRequestProperty("content-type", "application/json;charset=utf-8");
		urlConnection.setRequestProperty("accept", "application/json;chaeset=utf-8");
		// 得到请求的输出流对象
		OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream());
		// 把数据写入请求的Body
		// JSONObject reqheadj = JSONObject.fromObject(reqhead);
		out.write(jstr);
		out.flush();
		out.close();

		// 从服务器读取响应
		InputStream inputStream = urlConnection.getInputStream();
		String encoding = urlConnection.getContentEncoding();
		String body = IOUtils.toString(inputStream, encoding);
		System.out.println("body="+body);
		
		JSONObject bodyObject=JSONObject.parseObject(body);
		if(bodyObject.getString("resCode")!="000000"){
			return body;
		}
		
		String Rjson=body;//随行付返回的json数据
		
		RequestMessage requestMessage = JsonUtils.fromJson(Rjson,RequestMessage.class);

		String sign = requestMessage.getSign();
		String resData = requestMessage.getResData();

		// 验证签名，随行付公钥
		String publicKey = PublicPartUtils.publicKey;
		boolean signFlag = sign !=null && StringUtils.isNotBlank(resData) && RSAUtils.verify(resData, sign, publicKey);
		if (!signFlag)
			System.out.println("签名验证失败");//根据实际业务修改

		// 解密
		byte[] base64bs = Base64Utils.decode(resData);
		
		// DES解密
		String DesKey=PublicPartUtils.DESkey;
		byte[] debs = DESUtils.decrypt(base64bs, DesKey);
		
		String resDataDecrypt = new String(debs,"UTF-8");
		requestMessage.setResData(resDataDecrypt);	
		System.out.println("requestMessage="+JsonUtils.toJson(requestMessage));
		
		//测试
//		RequestMessage erm = JsonUtils.fromJson(json, RequestMessage.class);
//
//		String reqData = erm.getReqData();
//
//		// DES密钥加密
//		String DESkey = "12345678";
//		byte[] bs = DESUtils.encrypt(reqData.getBytes("UTF-8"), DESkey);
//		// 编码
//		String reqDataEncrypt = Base64Utils.encode(bs);
//		erm.setReqData(reqDataEncrypt);
//
//		// 合作商私钥签名
//		String RSAKey = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJ2RQPh70xBdszWvblWQM53BAodNNUdVE9gaLZpe2LUwv15BMxnur47gheaTQ3t3XIaGccre+clqaSkIN6niTcTIk5LgPHUD6Tp0CUqxHavn2lZy/AJ6vZ7yFTxZXmBckii7+bunT8EyNpZVhN3d3pIl3spNQyPxyV4vtfW+PqKxAgMBAAECgYBVh2ETAHPDMHl0rLNhcpLyELDErN48yCurZBpY7x8Gy101VoLckrls/ubwEAPTYykwRI5EJuDDuiU3BqTgbFz1kdayLV7YZSICgRZJEBtrtmoLku9zH2xFP2PY0dB5p8EdkPn4TsJfTyVER0PWy8IMWIhLenPyL2ubADnTTvyIAQJBAP+rFdsUsRi1ftZzQd1d+4vPotw1qoSi/q6Kp47hA+R4mhtmI2AQKLERTwvyxZ8u3JW1EpFsld4X3oGlzrhwqXECQQCdxZYbGLoPXhtrNN6RXe+lCt/TFiZYEF+sLntcn0YZ+0QHs897moNLGPZtIj/4nhAwUYcCd2a/JzKm/YvWJu1BAkAB5lyQNzQlsduSbmLT6UngPRfBuSheOfPYijE6j5N+1CKZB4ZFxXj379/9f71WNHvxJNpReFQYxWai4f+KQVQRAkBJXVbmtMHYYY9oc8ZHXKISYhMgqj0cWEjU3Sx6Loo/jKre1gtWU8xXwHze1L1gk8e9YDvitrktjEGui1paM/HBAkEArgDBrsWfNKqK0kwFG6r9HN/b4cj5VR1E7w89FJayKm9fzUbXeC1aESk4IfpteLibtX0onxVaWnseg5QKumIREw==";
//
//		erm.setSign(RSAUtils.sign(reqDataEncrypt, RSAKey));
//
//		System.out.println("erm1="+JsonUtils.toJson(erm));
//		String jstr = JsonUtils.toJson(erm);
//		String url = "http://106.37.197.53:38080/paygateway/pay.do";
//
//		URL urlt = new URL(url);
//		URLConnection urlConnection = urlt.openConnection();
//		// 设置doOutput属性为true表示将使用此urlConnection写入数据
//		urlConnection.setDoOutput(true);
//		// 定义待写入数据的内容类型，我们设置为application/x-www-form-urlencoded类型
//		urlConnection.setRequestProperty("content-type", "application/json;charset=utf-8");
//		urlConnection.setRequestProperty("accept", "application/json;chaeset=utf-8");
//		// 得到请求的输出流对象
//		OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream());
//		// 把数据写入请求的Body
//		// JSONObject reqheadj = JSONObject.fromObject(reqhead);
//		out.write(jstr);
//		out.flush();
//		out.close();
//
//		// 从服务器读取响应
//		InputStream inputStream = urlConnection.getInputStream();
//		String encoding = urlConnection.getContentEncoding();
//		String body = IOUtils.toString(inputStream, encoding);
//		System.out.println("body="+body);
//		
//		JSONObject bodyObject=JSONObject.parseObject(body);
//		if(bodyObject.getString("resCode")!="000000"){
//			return body;
//		}
//		
//		String Rjson=body;//随行付返回的json数据
//		
//		RequestMessage requestMessage = JsonUtils.fromJson(Rjson,RequestMessage.class);
//
//		String sign = requestMessage.getSign();
//		String resData = requestMessage.getResData();
//
//		// 验证签名，随行付公钥
//		String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCiZqyKJeaRJh+AU1EWJhkMXFPsQdVHKeP+tbqdYYw/Pi+vEJ4QhvVZ/YFcv7K8eBpMn71UPo8CP2Ere81qjdJrGDJXnQcRIcJe2TLJv070Vt0fNw4rBpkNJDdhSNwPtsT9UaAvrhi/tX8gvT+2gqZMEm7hl5L6PSA3W/sfFrAYZQIDAQAB";
//		
//		boolean signFlag = sign !=null && StringUtils.isNotBlank(resData) && RSAUtils.verify(resData, sign, publicKey);
//		if (!signFlag)
//			System.out.println("签名验证失败");//根据实际业务修改
//
//		// 解密
//		byte[] base64bs = Base64Utils.decode(resData);
//		
//		// DES解密
//		byte[] debs = DESUtils.decrypt(base64bs, "12345678");
//		
//		String resDataDecrypt = new String(debs,"UTF-8");
//		
//		requestMessage.setResData(resDataDecrypt);
//		
////		System.out.println("requestMessage="+JsonUtils.toJson(requestMessage));
		
		
		
		return JsonUtils.toJson(requestMessage);
	}
}
